﻿using LibBinary.DataSource;
using LibBinary.FileData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibBinary.FileDeclaration.Text
{
    public struct StructuredField
    {
        public string FieldName;
        public IFileDeclaration Declaration;
    }

    public class StructuredDeclaration : IFileDeclaration
    {
        private readonly StructuredField[] fields;

        public StructuredDeclaration(StructuredField[] fields)
        {
            this.fields = fields;
        }

        public AbstractFileData Read(TextFileInputSource src, AbstractFileData parentNode)
        {
            src.SkipChar('{');
            var ret = ReadFields(src, parentNode);
            src.SkipChar('}');
            return ret;
        }

        public StructuredData ReadFields(TextFileInputSource src, AbstractFileData parentNode)
        {
            var ret = new StructuredData(parentNode);
            ret.Data = new AbstractFileData[fields.Length];

            for (int i = 0; i < fields.Length; ++i)
            {
                if (src.ReadWord() != fields[i].FieldName)
                {
                    throw new ReadingFormatException("FieldName mismatch.");
                }
                src.SkipChar(':');

                var theField = new FieldData(ret);
                theField.FieldName = fields[i].FieldName;
                theField.Data = fields[i].Declaration.Read(src, theField);

                ret.Data[i] = theField;

                if (i != fields.Length - 1)
                {
                    src.SkipChar(',');
                }
                else
                {
                    src.TrySkipChar(',');
                }
            }

            return ret;
        }

        public void Write(TextFileOutputSource src, AbstractFileData data)
        {
            throw new NotImplementedException();
        }
    }
}
